<template>
  <basic-dialog
    v-model="visible"
    :title="dialogTitle"
    :submitBtnLoading="submitLoading"
    width="60%"
    :autoClose="false"
    @submit="handleSubmit"
  >
    <el-form
      :model="formData"
      :rules="rules"
      label-width="120px"
      ref="formRef"
      v-if="visible"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="菜单类型" prop="menuType">
            <el-radio-group
              v-model="formData.menuType"
              @change="handleMenuChange"
            >
              <el-radio-button
                v-for="item in filterMenuOptionList"
                :key="item.value"
                :value="item.value"
                >{{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上级菜单" prop="parentId">
            <pre-menu-cascader
              v-if="visible"
              v-model="formData.parentId"
              :menuType="formData.menuType"
              style="width: 100%"
            ></pre-menu-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="`${menuTypeLabel}名称`" prop="name">
            <el-input
              v-if="formData.menuType !== 'button'"
              v-model="formData.name"
              show-word-limit
              :maxlength="10"
              :min="2"
            />
            <BasicCrudTableSelect
              v-else
              v-model:formData="formData"
              label="按钮"
              boxType="edit"
              :crudProps="{
                apiSource: '/system/buttonManage',
                option: buttonOption,
              }"
              prop="name"
              :comProps="{
                comType: 'direct',
                selectedKey: 'code',
                saveFieldMap: [
                  'name',
                  'iconCss',
                  'functionName',
                  'expression',
                  'code',
                ],
              }"
            ></BasicCrudTableSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="`${menuTypeLabel}编码`" prop="code">
            <el-input
              v-model="formData.code"
              :disabled="formData.menuType === 'button'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="`${menuTypeLabel}图标`" prop="iconCss">
            <basic-crud-icon-select
              v-model="formData.iconCss"
              :disabled="formData.menuType === 'button'"
            ></basic-crud-icon-select>
          </el-form-item>
        </el-col>
        <el-col v-if="formData.menuType === 'button'" :span="12">
          <el-form-item label="方法名" prop="functionName">
            <el-input
              v-model="formData.functionName"
              :disabled="formData.menuType === 'button'"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="formData.menuType === 'button'" :span="12">
          <el-form-item label="if表达式" prop="expression">
            <el-input
              v-model="formData.expression"
              :disabled="formData.menuType === 'button'"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="formData.menuType === 'menu'" :span="12">
          <el-form-item label="路由路径" prop="route">
            <el-input v-model="formData.route" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.menuType === 'menu'">
          <el-form-item label="组件路径" prop="compUrl">
            <el-input v-model="formData.compUrl" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.menuType === 'button'">
          <el-form-item label="权限标识" prop="permissionFlag">
            <el-input v-model="formData.permissionFlag" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="`${menuTypeLabel}排序`" prop="orderNum">
            <el-input-number
              v-model="formData.orderNum"
              style="width: 100%"
              step-strictly
              :step="10"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.menuType !== 'button'">
          <el-form-item label="指定角色">
            <el-input
              v-model="formData.specifyRoles"
              placeholder="超级管理员是root,管理员是admin,三员管理员等于三员对应的角色名"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="是否显示" prop="display">
            <el-radio-group v-model="formData.display">
              <el-radio-button :value="true">显示</el-radio-button>
              <el-radio-button :value="false">隐藏</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <template #label>
              <div class="flex_center">
                <span class="pr_8">状态</span>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="停用状态页面不可见"
                  placement="top-start"
                >
                  <el-icon size="16"><InfoFilled></InfoFilled></el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-radio-group v-model="formData.status">
              <el-radio-button value="Enabled">启用</el-radio-button>
              <el-radio-button value="Disabled">停用</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="是否缓存" v-if="formData.menuType === 'menu'">
            <el-radio-group v-model="formData.cacheable">
              <el-radio-button :value="true">缓存</el-radio-button>
              <el-radio-button :value="false">不缓存</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否外链" v-if="formData.menuType === 'menu'">
            <el-radio-group v-model="formData.outLink">
              <el-radio-button :value="true">是</el-radio-button>
              <el-radio-button :value="false">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="描述">
            <el-input v-model="formData.des" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </basic-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { apiAdd, apiEdit } from '@/apis/system/menuManage'
import { apiGetList as apiGetButtonList } from '@/apis/system/buttonManage.js'
import PreMenuCascader from './PreMenuCascader.vue'
import { nextTick, watch } from 'vue'
import { cloneDeep } from 'lodash'
// 菜单类型
const menuOptionList = [
  {
    value: 'folder',
    label: '目录',
  },
  {
    value: 'menu',
    label: '菜单',
  },
  {
    value: 'button',
    label: '按钮',
  },
]
const buttonOption = {
  menu: false,
  header: false,
  searchSpan: 8,
  height: '40vh',
  column: [
    {
      label: '编号',
      prop: 'code',
      search: true,
      sortable: true,
      maxlength: 30,
      minlength: 2,
      showWordLimit: true,
      with: 50,
    },
    {
      label: '名称',
      prop: 'name',
      search: true,
      sortable: true,
      maxlength: 20,
      minlength: 2,
      showWordLimit: true,
    },
    {
      label: '按钮位置',
      type: 'select',
      prop: 'buttonType',
      slot: true,
      sortable: true,
      dicData: [
        {
          label: '表外',
          value: 'out_table',
        },
        {
          label: '行内',
          value: 'in_line',
        },
      ],
    },
    {
      label: '方法名',
      prop: 'functionName',
    },
    {
      label: 'if表达式',
      prop: 'expression',
    },
  ],
}
const filterMenuOptionList = ref([])
const props = defineProps({
  dialogType: {
    type: String,
    default: 'add',
  },
  editData: {
    type: Object,
    default: () => ({}),
  },
  submitSuccess: {
    type: Function,
    default: () => {},
  },
})

const dialogTitle = computed(() => {
  if (['add', 'addSon'].includes(props.dialogType)) {
    return '新增' + menuTypeLabel.value
  } else if (props.dialogType === 'edit') {
    return '编辑' + menuTypeLabel.value
  }
})
const defaultFormData = {
  menuType: 'folder',
  display: true,
  cacheable: false,
  status: 'Enabled',
  outLink: false,
  resControlType: 'http', //无用属性
}
const formData = ref(defaultFormData)
const menuTypeLabel = computed(
  () =>
    filterMenuOptionList.value.find(
      (item) => item.value === formData.value.menuType
    )?.label
)
const visible = defineModel()
const rules = ref({
  name: [
    {
      required: true,
      message: `请输入名称`,
      trigger: formData.value.menuType === 'buttom' ? 'change' : 'blur',
    },
    {
      min: 2,
      max: 10,
      message: '长度在 2 到 10 个字符',
      trigger: 'change',
    },
  ],
  code: [{ required: true, message: '请输入编号', trigger: 'blur' }],
  compUrl: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
  route: [{ required: true, message: '请输入路由路径', trigger: 'blur' }],
  // iconCss: [{ required: true, message: '请选择图标', trigger: 'change' }],
  permissionFlag: [
    { required: true, message: '请输入权限表示', trigger: 'blur' },
  ],
  orderNum: [
    {
      type: 'number',
      required: true,
      message: '请输入排序号',
      trigger: ['blur', 'change'],
    },
  ],
})

// 菜单切换
const handleMenuChange = () => {
  formData.value = defaultFormData
  formRef.value.clearValidate()
}

const submitLoading = ref(false)
const formRef = ref()
// 确认按钮触发
const handleSubmit = async () => {
  await formRef.value.validate()
  submitLoading.value = true
  let apiFun = ['add', 'addSon'].includes(props.dialogType) ? apiAdd : apiEdit
  const cloneData = cloneDeep(formData.value)
  if (Array.isArray(cloneData.parentId)) {
    cloneData.parentId = cloneData.parentId[cloneData.parentId.length - 1]
  }
  await apiFun(cloneData, submitLoading)
  ElMessage.success('保存成功！')
  props.submitSuccess && props.submitSuccess()
  visible.value = false
}

// 监听弹窗打开关闭
watch(
  () => visible.value,
  (newV) => {
    if (newV) {
      if (props.dialogType === 'edit') {
        formData.value = props.editData
        filterMenuOptionList.value = menuOptionList
      } else if (props.dialogType === 'add') {
        filterMenuOptionList.value = menuOptionList
        formData.value = defaultFormData
      } else if (props.dialogType === 'addSon') {
        if (props.editData.menuType === 'button') {
          filterMenuOptionList.value = menuOptionList.slice(2)
        } else {
          filterMenuOptionList.value = menuOptionList.slice(0, 2)
        }
        formData.value = Object.assign(defaultFormData, props.editData)
        console.log(formData.value, 'formData.value')
      }
    } else {
      formRef.value && formRef.value.resetFields()
    }
  },
  {
    immediate: true,
    deep: true,
  }
)
</script>

<style lang="scss" scoped>
.el-col {
  margin: 5px 0;
}
.el-input,
.el-dropdown {
  width: 100%;
}
</style>
